const {
  controller
} = require('../../controllers/Controller.js');

// pages/cart/submitOrder/submitOrder.js
const Controllers = require('../../controllers/Controller.js').controller;
const app = getApp();



Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalStype: '',
    cartList: [],
    price: 0,
    num: 0,
    couponPrice: 0,
    couponAccountId: '',
    inputLengt: 0,
    desc: '',
    isBalance: true,
    payType: "wx",
    isCoupon: true,
    total: 0,
    paytotal: 0,
    shopId: '',
    isGood: false,
    marketNo: null,
    options: '',
    myInformationdata: {
      vip: 0,
      balance: 0
    },
    userId: '',
    coupongoodsids: [],
    isuseCoupon: 1,
    getMyCouponPagenum: 0,
    isPin: true,
    discount: 1,
    openDiscount: "",
    list: [],
    index: "",
    staffId: "",
    staffName: "",
    dialogShow: false,
    buttons: [{
      text: '取消'
    }, {
      text: '确定'
    }],
    staffBox: true,
    showModalStatus: false,
    animationData: {},
    isMail: 0,
    EXPRESS: "",

    address: null,
    addressList: [],
    openGoShop: false,
    openGoHome: true,
    dialogShowAddress: false,
    currentAddressIndex: 0,
    cartPayFirstOrderNo:''
  },
  onLoad: function (options) {
    // this.judgePay()
    this.setData({
      globalStype: app.globalData.globalStype
    })
    if (app.globalData.shopId) {
      this.setData({
        shopId: app.globalData.shopId
      })
    }
    if (options.shopId) {
      app.globalData.shopId = options.shopId
      this.setData({
        shopId: options.shopId
      })
      wx.setStorageSync('shopId', options.shopId)
    }
    if (options) {
      this.setData({
        options: options
      })
      this.getcartlists()
    }

    if (options.couponAccountId) {
      this.setData({
        couponAccountId: options.couponAccountId
      })
    }
  },

  //判断是否隐藏直邮到付
  // judgePay(){
  //   let value={}
  //   value.ms="EXPRESS"
  //   value.data={shopId:wx.getStorageSync('shopId')}
  //   value.data=JSON.stringify(value.data)
  //   controller.judgePay(value).then(res=>{
  //     this.setData({
  //       EXPRESS:res.data.EXPRESS
  //     })
  //   })
  // },



  getcartlists() {
    // 获取列表
    let options = this.data.options
    let cartList
    console.log(options.list)
    if (options.list) { //购物车跳转过来的
      cartList = JSON.parse(decodeURIComponent(options.list))
    } else if (options.isGood) { //直接购买
      console.log(options.good)
      let good = JSON.parse(decodeURIComponent(options.good))
      console.log("good", good)
      if (!good.num) {
        good.num = 1
      }
      good.goodsType = good.type
      cartList = []
      cartList.push(good)
      this.setData({
        isGood: options.isGood,
        marketNo: options.marketNo
      })
    }
    // 判断所有商品是否都开启直邮到家
    const openGoHome = cartList.some(item => !!item.openGoHome)
    this.setData({
      cartList,
      openGoHome
    })

  },
  cart(isMyCouponPage = false) {
    var cartList = this.data.cartList;
    var total = 0
    var num = 0
    var paytotal = 0
    var norPaytotal = 0
    var cloPaytotal = 0
    let vip = this.data.myInformationdata.vip
    cartList.forEach(item => {
      if (item.goodsType == 2) {
        this.setData({
          isBalance: false
        })
      }
      // 用户处于对应身份且商品开启对应价格
      var price = 0;
      if (item.openAgent && item.agentPrice) {
        price = item.agentPrice;
      } else if (item.openShareholder && item.shareholderPrice) {
        price = item.shareholderPrice;
      } else if ((vip == 1 || vip == 3 || vip == 4) && item.vipState && item.vipPrice >= 0) {
        price = item.vipPrice;
      } else if (vip != 0 && item.memberState && item.memberPrice >= 0) {
        price = item.memberPrice;
      } else {
        price = item.price;
      }
      if (this.data.marketNo && item.marketList && item.marketList.length > 0 && item.marketList[0].pinPrice && item.marketList[0].pinPrice > 0) {
        price = item.marketList[0].pinPrice
      }

      if (item.goodsType == 2) {
        cloPaytotal = cloPaytotal + price * item.num;
      } else {
        norPaytotal = norPaytotal + price * item.num;
      }
      total = cloPaytotal + norPaytotal;
      num = num + item.num
    });
    if (this.data.isCoupon && this.data.coupongoodsids.length >= 0) {
      paytotal = (norPaytotal - this.data.couponPrice) * (this.data.openDiscount == 1 ? this.data.discount : 1) + cloPaytotal
    } else {
      paytotal = norPaytotal * (this.data.openDiscount == 1 ? this.data.discount : 1) + cloPaytotal
    }

    this.setData({
      cloPaytotal,
      norPaytotal,
      total,
      paytotal,
      num,
    })
    if (!isMyCouponPage) {
      this.getMyCouponPage()
    }

  },
  myInformation() {
    //获取数据
    Controllers.myInformation({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        myInformationdata: res.data.accountRelation,
        userId: res.data.id
      })
      this.cart()

    }).catch(res => {
      this.cart()

    })
  },
  //获取未使用的优惠券列表
  getMyCouponPage() {
    var cartList = this.data.cartList;
    let list = cartList.filter(item => item.goodsType == 0)
    let list2 = cartList.filter(item => item.goodsType == 1)
    if ((list.length <= 0 && list2.length <= 0) || this.data.marketNo) {
      this.setData({
        isCoupon: false
      })

    } else {
      let goodsIdsattr = [];
      for (let item of this.data.cartList) {
        goodsIdsattr.push(item.goodsId)
      }
      let goodsIds = goodsIdsattr.join(',')

      Controllers.canUseCoupon({
        shopId: this.data.shopId,
        accountId: wx.getStorageSync('accountId'),
        goodsIds: goodsIds,
        totalPrice: this.data.total
      }).then(res => {
        if (res.code == 1) {
          console.log('123', this.data.couponAccountId);

          if (res.data && res.data.length > 0 && this.data.isuseCoupon == 1) {
            let ishascoupon = false
            for (let item of res.data) {
              if (this.data.couponAccountId == item.id) {
                console.log('123', this.data.couponAccountId, item.id);
                ishascoupon = true;
                this.setData({
                  couponPrice: item.couponPrice
                })
                break;
              }
            }
            if (!ishascoupon) {
              this.setData({
                couponPrice: res.data[0].couponPrice,
                couponAccountId: res.data[0].id
              })
              if (res.data[0].couponType == 2) {
                this.setData({
                  coupongoodsids: res.data[0].ids.split(',')
                })
              }
            }
          } else {
            this.setData({
              couponPrice: 0,
              couponAccountId: ''
            })
          }
        }
        this.cart(true)
      }).catch(res => {
        this.cart(true)
      })
    }
  },
  gocoupon() {
    let goodsIdsattr = [];
    for (let item of this.data.cartList) {
      goodsIdsattr.push(item.goodsId)
    }
    let goodsIds = goodsIdsattr.join(',')
    wx.navigateTo({
      url: '/pages/cart/coupon/coupon?totalPrice=' + this.data.total + '&goodsIds=' + goodsIds + '&couponAccountId=' + this.data.couponAccountId
    })
  },

  onShow: function () {
    if (app.globalData.coupon && this.data.isCoupon) {
      this.setData({
        couponPrice: app.globalData.coupon.couponPrice,
        couponAccountId: app.globalData.coupon.id
      })
    }
    if (app.globalData.isuseCoupon) {
      this.setData({
        isuseCoupon: app.globalData.isuseCoupon
      })
    }
    this.myInformation()
    this.getShopDiscount()
    this.getStaffList()
    this.getAddressList()
  },
  onUnload: function () {
    this.setData({
      couponPrice: 0,
      couponAccountId: ''
    })
    if (app.globalData.coupon) {
      app.globalData.coupon.couponPrice = 0
      app.globalData.coupon.id = ''
    }
  },
  //键盘输入触发
  length(e) {
    let length = e.detail.value.length
    let value = e.detail.value
    // console.log(length)
    this.setData({
      desc: value,
      inputLengt: length
    })
  },
  //跳转详情
  goDetail(e) {
    let url = e.currentTarget.dataset['url'];
    wx.navigateTo({
      url: url
    })
  },
  //选择支付方式
  selectType(e) {
    let payType = e.currentTarget.dataset['type'];
    if (payType == "yr") {
      if (this.data.isBalance) {
        this.setData({
          payType
        })
      }
    } else {
      this.setData({
        payType
      })
    }
  },
  //删除商品
  deleteCart(e) {
    let index = e.currentTarget.dataset['index'];
    let ids
    let cartList = this.data.cartList
    let num = 0
    let total = 0
    ids = cartList[index].id
    wx.showModal({
      title: "是否删除该商品",
      success: (res) => {
        if (res.confirm) {
          Controllers.delGoods({
            shopId: this.data.shopId,
            cartIds: ids
          }).then(res => {
            if (res.code == 1) {
              cartList.splice(index, 1);
              if (cartList.length == 0) {
                wx.reLaunch({
                  url: "/pages/cart/index/index"
                })
              }
              this.setData({
                cartList
              })
              this.cart()
              wx.showToast({
                title: "删除成功",
                icon: 'none',
                duration: 800
              });
            }
          })
        }
      }
    })

  },
  //支付
  pay() {
    var balance = this.data.myInformationdata.balance;
    if (this.data.payType == "yr" && this.data.paytotal > balance) {
      wx.showToast({
        title: "余额不足",
        icon: 'none',
        duration: 800
      });
      return
    } else if (this.data.isMail) {
      // 直邮到家
      this.goHome()
    }
    //  else if (!this.data.openGoHome) {
    //   // 仅支持到店
    //   this.onlyGoShop()
    // } 
    else {
      // 到店自取
      this.setData({
        dialogShow: true
      })
    }
  },
  // 直邮到家
  goHome() {
    if (this.data.address) {
      this.setData({
        dialogShow: true
      })
    } else {
      wx.showToast({
        title: '请选择地址后再提交订单',
        icon: 'none'
      })
    }
  },
  onlyGoShop() {
    wx.showModal({
      title: "提示",
      content: '该商品仅支持到店',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            dialogShow: true
          })
        }
      }
    })
  },

  //购物车支付
  cartPay() {
    let ids = []
    this.data.cartList.forEach(item => {
      ids.push(item.id)
    })
    ids = ids.join(',')
    let data = {
      shopId: this.data.shopId,
      cartIds: ids,
      desc: this.data.desc,
      shopAccountId: this.data.staffId,
      isMail: this.data.isMail
    }
    if (this.data.couponAccountId) {
      data.couponAccountId = this.data.couponAccountId
    }
    if (this.data.isMail == 1) {
      if (this.data.address) {
        data.addressId = this.data.address.id
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择收货地址',
        })
        return
      }
    }
    Controllers.cartSettlement(data).then(res => {
      if (res.code == 1) {
        if (this.data.payType == "yr" || this.data.paytotal <= 0) {
          this.yrPay(res.data.orderNo)
        } else {
          this.weChatPay(res.data)
          // this.paySuccess(res.data)

        }
        // 购物车支付保存商品列表第一个orderNo（PY开头），用于后续查看订单详情，非该支付订单号（TO开头）
        // 直接购买不需要此操作,支付订单号（PY开头）
        this.setData({
          couponPrice: 0,
          couponAccountId: '',
          cartPayFirstOrderNo:res.data.orderGoodsList[0].orderNo
        })
        if (app.globalData.coupon) {
          app.globalData.coupon.couponPrice = 0
          app.globalData.coupon.id = ''
        }
      }
    })
  },
  //直接购买
  goodPay() {
    let goodsId = this.data.cartList[0].goodsId
    let num = this.data.cartList[0].num
    let data = {
      shopId: this.data.shopId,
      goodsId: goodsId,
      num: num,
      couponAccountId: this.data.couponAccountId,
      desc: this.data.desc,
      shopAccountId: this.data.staffId,
      isMail: this.data.isMail
    }
    if (this.data.isMail == 1) {
      if (this.data.address) {
        data.addressId = this.data.address.id
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择收货地址',
        })
        return
      }
    }
    this.setData({
      goodsId: goodsId
    })
    if (this.data.marketNo) {
      data.marketNo = this.data.marketNo
    }

    Controllers.goodsSettlement(data).then(res => {
      if (res.code == 1) {
        this.setData({
          orderId: res.data.orderNo
        })
        if (this.data.payType == "yr" || this.data.paytotal <= 0) {
          this.yrPay(res.data.orderNo, res.data.id)
        } else {
          this.weChatPay(res.data, res.data.id)
          // this.paySuccess(res.data)
        }
        this.setData({
          couponPrice: 0,
          couponAccountId: ''
        })
        if (app.globalData.coupon) {
          app.globalData.coupon.couponPrice = 0
          app.globalData.coupon.id = ''
        }
      }
    })
  },
  //加减商品数量
  addSubtract(e) {
    if (this.data.marketNo) {
      return
    }
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let num = 0;
    let total = 0
    if (type == "add") {
      cartList[index].num += 1
    } else if (cartList[index].num > 1) {
      cartList[index].num -= 1
    }
    if (this.data.isGood) {
      this.setData({
        cartList
      })
      this.cart()
    } else {
      Controllers.updateCart({
        shopId: this.data.shopId,
        cartId: cartList[index].id,
        num: cartList[index].num
      }).then(res => {
        if (res.code == 1) {
          this.setData({
            cartList
          })
          this.cart()
        }
      })
    }
  },
  changenums(e) {
    if (this.data.marketNo) {
      return
    }
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;

    let num = Number(e.detail.value)
    if (!num || num <= 0) num = 1
    cartList[index].num = num

    if (this.data.isGood) {
      this.setData({
        cartList
      })
      this.cart()
    } else {
      Controllers.updateCart({
        shopId: this.data.shopId,
        cartId: cartList[index].id,
        num: cartList[index].num
      }).then(res => {
        if (res.code == 1) {
          this.setData({
            cartList
          })
          this.cart()
        }
      })
    }
  },
  //余额支付
  yrPay(orderNo, orderId) {
    console.log(orderId)
    Controllers.balancePay({
      shopId: this.data.shopId,
      orderNo: orderNo
    }).then(res => {
      if (res.code == 1) {
        setTimeout(() => {
          let goodsType = this.data.cartList[0].goodsType;
          let goodsId = this.data.cartList[0].goodsId;
          orderNo = this.data.isGood? orderNo : this.data.cartPayFirstOrderNo;
console.log(orderNo,'123',this.data.isGood,this.data.cartPayFirstOrderNo);
          if (this.data.isGood) {
            // wx.navigateBack({
            //   delta: 1
            // })
            if (this.data.cartList[0].isPin == true) {
              wx.showToast({
                title: '拼团支付完成',
                duration: 2000
              })
              setTimeout(function () {
                // wx.navigateTo({
                //   url: '/pages/my/service-order/service-order?id=1',
                // })
                wx.navigateTo({
                  url: '/pages/my/my-index/my-index',
                })
              }, 2000)
            } else {
              if (goodsType == 0) {
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId=' + goodsId + "&orderId=" + orderId + "&goodsType=" + goodsType + "&orderNo=" + orderNo,
                })
              } else {
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId=' + goodsId + "&orderId=" + orderId + "&goodsType=1" + "&orderNo=" + orderNo,
                })
              }
            }
          } else {
            // wx.reLaunch({
            //   url: "/pages/cart/index/index"
            // })
            wx.navigateTo({
              url: '/pages/cart/submitOrder/success/success?goodsType=1' + "&orderNo=" + orderNo
            })
          }
        }, 1000)

        // wx.showToast({
        //   title: "支付成功",
        //   icon: 'none',
        //   duration: 1000
        // });
      }
    })
  },
  paySuccess(data) {
    Controllers.paySuccess({
      shopId: this.data.shopId,
      orderNo: data.orderNo,
      orderId: data.id,
      accountId: data.accountId ? data.accountId : ''
    }).then(res => {
      if (res.code == 1) {
        var that = this;
        setTimeout(() => {
          if (that.data.isGood) {
            wx.navigateBack({
              delta: 1
            })
          } else {
            wx.reLaunch({
              url: "/pages/cart/index/index"
            })
          }
        }, 1000)

        wx.showToast({
          title: "下单成功",
          icon: 'none',
          duration: 1000
        });
      }
    })
  },

  weChatPay(data, orderId) {
    var that = this;
    let openId = app.globalData.openId
    let orderNo = data.orderNo
    Controllers.weChatPay({
      shopId: this.data.shopId,
      orderNo: orderNo,
      frontUrl: "mp:///pages/Index/Index",
      openId: openId
    }).then(res => {
      // let url=res.data;
      // url=encodeURIComponent(url);
      // console.log(url);
      // wx.redirectTo({
      //   url: '/pages/weixinlink/weixinlink?url='+url,
      // })
      let data = JSON.parse(res.data);
      console.log(data)
      console.log(orderId)
      wx.requestPayment({
        nonceStr: data.nonceStr,
        package: data.package,
        paySign: data.paySign,
        timeStamp: data.timeStamp,
        signType: data.signType,
        success(res) {
          let goodsType = that.data.cartList[0].goodsType;
          let goodsId = that.data.cartList[0].goodsId;
          if(!that.data.isGood){
            orderNo = that.data.cartPayFirstOrderNo;
          }
          let order = orderId;
          if (that.data.isGood) {
            // wx.navigateBack({
            //   delta: 1
            // })
            if (that.data.cartList[0].isPin == true) {
              wx.showToast({
                title: '拼团支付完成',
                duration: 2000
              })
              setTimeout(function () {
                // wx.navigateTo({
                //   url: '/pages/my/service-order/service-order?id=1',
                // })
                wx.navigateTo({
                  url: '/pages/my/my-index/my-index',
                })
              }, 2000)
            } else {
              if (goodsType == 0) {
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId=' + goodsId + "&orderId=" + order + "&goodsType=" + goodsType + "&orderNo=" + orderNo,
                })
              } else {
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId=' + goodsId + "&orderId=" + order + "&goodsType=1" + "&orderNo=" + orderNo,
                })
              }
            }
          } else {
            // wx.reLaunch({
            //   url: "/pages/cart/index/index"
            // })
            wx.navigateTo({
              url: '/pages/cart/submitOrder/success/success?goodsType=1' + "&orderNo=" + orderNo
            })
          }
          wx.showToast({
            title: "支付成功",
            icon: 'none',
            duration: 1000
          });
        },
        fail(res) {
          setTimeout(() => {
            // if(that.data.isGood){
            wx.navigateBack({
              delta: 1
            })
            // }else{
            //   wx.reLaunch({
            //     url: "/pages/cart/index/index"
            //   })
            // }
          }, 1000)

          wx.showToast({
            title: "支付失败",
            icon: 'none',
            duration: 1000
          });
        }
      })
    }).catch(res => {

      setTimeout(() => {
        // if(that.data.isGood){
        wx.navigateBack({
          delta: 1
        })
        // }else{
        //   wx.reLaunch({
        //     url: "/pages/cart/index/index"
        //   })
        // }
      }, 1000)

      wx.showToast({
        title: "支付失败",
        icon: 'none',
        duration: 1000
      });
    })
  },

  //获取商圈折扣
  getShopDiscount() {
    controller.shopDiscount({
      shopId: wx.getStorageSync('shopId')
    }).then(res => {
      if (res.data.openDiscount == 1) {
        this.setData({
          discount: JSON.parse(res.data.discount) / 100,
          openDiscount: res.data.openDiscount,
          discountText: res.data.discount
        })
      } else {
        this.setData({
          discount: 1,
          openDiscount: res.data.openDiscount,
          discountText: res.data.discount
        })
      }
      this.cart(true)
    })
  },

  //获取员工列表
  getStaffList() {
    let shopId = wx.getStorageSync('shopId')
    Controllers.getStaffList({
      shopId: shopId
    }).then(res => {
      this.setData({
        list: res.data
      })
    })
  },

  //绑定员工
  // bindStaff(e){
  //   let index=e.detail.value
  //   this.setData({
  //     index:index,
  //     staffId:this.data.list[index].id,
  //     staffName:this.data.list[index].nick
  //   })
  // },

  tapDialogButton(e) {
    let index = e.detail.index
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ['_uuqoPgxng4xi9Zfhr3xt41_NQrso8WTCUn6M9JoGYs'],
      success: res => {
        console.log(res)
      },
      complete: () => {
        if (index == 1) {
          if (that.data.isGood) {
            that.goodPay()
          } else {
            that.cartPay()
          }
        } else {

        }
      }
    })
    this.setData({
      dialogShow: false
    })
  },

  //关闭员工选框
  closeOpen() {
    this.setData({
      staffBox: false
    })
  },

  //显示弹框
  showModal: function () {
    this.setData({
      showModalStatus: true
    })
  },
  // 隐藏弹框
  hideModal: function () {
    this.setData({
      showModalStatus: false
    })
  },

  //选择员工
  selectStaff(e) {
    let index = e.currentTarget.dataset.index
    console.log(e)
    if (index === this.data.selectIndex) {
      this.setData({
        selectIndex: "",
        staffId: "",
        staffName: ""
      })
    } else {
      this.setData({
        selectIndex: index
      })
    }
  },

  //确定员工
  defineStaff() {
    if (this.data.selectIndex || this.data.selectIndex === 0) {
      this.setData({
        staffId: this.data.list[this.data.selectIndex].id,
        staffName: this.data.list[this.data.selectIndex].nick
      })
    }
    this.hideModal()
  },

  //跳转员工详情
  selectStaffDetail(e) {
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let value = this.data.list[index]
    wx.navigateTo({
      url: '/pages/selecStaffDetail/selecStaffDetail?staffDetail=' + encodeURIComponent(JSON.stringify(value)),
    })
  },

  //打开地址弹窗
  toSelectAddress() {
    this.setData({
      dialogShowAddress: true
    })
  },
  toAddressPage() {
    wx.navigateTo({
      url: '/pages/my/my-index/selectAddress',
    })
  },
  changeAddress(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      currentAddressIndex: index
    })
  },
  closeAddress() {
    this.setData({
      dialogShowAddress: false
    })
  },
  handleAddress() {
    let index = this.data.currentAddressIndex
    const address = this.data.addressList[index]
    this.setData({
      address
    })
    this.closeAddress()
  },
  //获取默认地址
  // getDefaultAddress() {
  //   controller.getDefaultAddress().then(res => {
  //     this.setData({
  //       address: res.data
  //     })
  //   })
  // },

  //获取地址列表
  getAddressList() {
    controller.getAddressList().then(res => {
      if (res.data) {
        let address = null
        if (res.data[0].isChoice) { //默认地址添加
          address = res.data[0]
        }
        this.setData({
          address,
          addressList: res.data,
        })
      }
    })
  },
  //是否需要配送地址
  isAddress(e) {
    let isMail = e.currentTarget.dataset.ismail
    this.setData({
      isMail: isMail
    })
  }
})